<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="basicConfig" :questions="basicQuestions" ref="base" />
    </BaseCollapse>

    <BaseCollapse title="借阅档案列表">
      <DynamicForm :config="borrowingListAddConfig" :questions="borrowingListAddQuestions" ref="borrowList" v-if="['ADD', 'UPDATE'].includes(state.showType)" />
      <DynamicTable :config="borrowingListViewTableConfig" :tables="borrowingListViewTable" v-if="['VIEW', 'AUDIT'].includes(state.showType)"></DynamicTable>
    </BaseCollapse>

    <BaseCollapse title="借阅信息">
      <DynamicForm :config="borrowingAddConfig" :questions="borrowingAddQuestions" ref="borrowInformation" v-if="['ADD', 'UPDATE'].includes(state.showType)">
        <template #borrowDuration="{ data }">
          <a-input-number min="1" max="999" v-model:value="data.borrowDuration" @blur.native="borrowDurationBlur($event, data.borrowDuration)"></a-input-number>
        </template>

        <template #expirationReminder>
          <!-- 借阅时间大于5天 -->
          <div v-if="borrowingDurationObj.isLargerThan === true">
            <span>{{ hasLargerThan }}</span>
          </div>

          <div v-else-if="borrowingDurationObj.isLargerThan === false">
            <span>{{ hasLessThan }}</span>
          </div>
        </template>
      </DynamicForm>
      <DynamicForm :config="borrowingViewConfig" :questions="borrowingViewQuestions" v-if="['VIEW', 'AUDIT'].includes(state.showType)"></DynamicForm>
    </BaseCollapse>

    <!-- <BaseCollapse v-if="['AUDIT'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="approvalOpinionsConfig" :questions="approvalOpinionsQuestions" ref="approvalOpinions" />
    </BaseCollapse> -->

    <ApprovalDetail v-if="['VIEW', 'AUDIT'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>

    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="state.showType !== 'AUDIT'" @click="goBack">返回</a-button>
      <a-button @click="savePageInfo(0)" v-if="['ADD', 'UPDATE'].includes(state.showType)">暂存</a-button>
      <a-button type="primary" @click="savePageInfo(1)" v-if="['ADD', 'UPDATE'].includes(state.showType)">提交</a-button>
      <!-- <a-button type="primary" @click="toUpdate" v-if="['VIEW'].includes(state.showType) && (query.status === '1' || query.status === '3')">编辑</a-button> -->
      <a-button type="primary" @click="toUpdate" v-if="['VIEW'].includes(state.showType) && (state.status == '1' || state.status == '3')">编辑</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import ApprovalDetail from '@/components/approval-details/index.vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { HOST } from '@/config';
import { Api, archivesBorrowAudit, archivesBorrowSave, archivesBorrowFindBorrowType, archivesBorrowFindFileListByFileName, archivesBorrowGetBorrowFileList } from '@/config/api/archivesBorrow';
import { Api as searchManageApi, advancedQueryPreview } from '@/config/api/searchManage';
import { formStoreWithOut } from '@/store/modules/form';
import { useUserStoreWithOut } from '@/store/modules/user';
import { Modal, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { filter } from 'rxjs/operators';
import { computed, getCurrentInstance, nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import indexService from './index.service';

const router = useRouter();
const { query } = useRoute();
const { proxy }: any = getCurrentInstance();

const formStore = formStoreWithOut();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'AUDIT' 'UPDATE'
  borrowTypeDictionary: {}, // 借阅类型key-value
  status: null
});

state.showType = query.showType as string;

const base = ref(null); // 基础信息
const borrowList = ref(null); // 借阅档案列表
const borrowInformation = ref(null); // 借阅信息
const approvalOpinions = ref(null); // 审批意见

const borrowIngListAllData = ref<Array<any>>([]); // 存放借阅档案列表文件数据
const selectFilename = ref<String>(''); // 选中的文件名称
const accessToken = useUserStoreWithOut().getToken;

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

const approvalGoBack = (cb: any) => {
  cb?.();
};

// 基础信息
const basicQuestions = reactive(indexService.getBasicQuestions());
const basicConfig: any = {
  queryUrl: ['ADD'].includes(state.showType) ? Api.archivesBorrowAutoProductFormInfo : Api.archivesBorrowGet,
  protType: ['ADD'].includes(state.showType) ? 'post' : 'get',
  urlName: ['ADD'].includes(state.showType) ? '' : query.id,
  noGetDataParams: true,
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};

// 借阅档案列表
// 申请
const borrowingListAddQuestions = reactive(indexService.getBorrowingListAddQuestions({ showType: state.showType }));
const borrowingListAddConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
// 详情
const borrowingListViewTable = reactive(indexService.getBorrowingListTables());
const borrowingListViewTableConfig = {
  queryUrl: Api.archivesBorrowGetBorrowFileList,
  protType: 'post',
  params: { id: query.id },
  scroll: { x: '1500px' }
};

// 借阅信息
// 申请
const borrowingAddQuestions: any = reactive(indexService.getBorrowingAddQuestions());
const borrowingAddConfig: any = {
  queryUrl: ['UPDATE'].includes(state.showType) ? Api.archivesBorrowGet : '',
  protType: 'get',
  urlName: query.id,
  labelCol: 8,
  wrapperCol: 22,
  grid: 8,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod(data) {
    for (let i of borrowingAddQuestions) {
      for (let j in data) {
        if (i.key === j) {
          i.value = data[j];
        }
      }
    }
    borrowDurationBlur({ isTrusted: true }, data['borrowDuration']);
    state.status = data.status;
  }
};
// 详情
const borrowingViewQuestions = reactive(indexService.getBorrowingViewQuestions());
const borrowingViewConfig: any = {
  queryUrl: Api.archivesBorrowGet,
  protType: 'get',
  urlName: query.id,
  labelCol: 8,
  wrapperCol: 22,
  grid: 8,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod: (data) => {
    state.status = data.status;
    return data;
  }
};

// 审批意见
const approvalOpinionsQuestions = reactive(indexService.getApprovalOpinionsQuestions());
const approvalOpinionsConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};

const subscribeFormSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    if (item.key === 'CUSTOMSELECTSERVE' && item.value.key === 'name') {
      // 文件名称
      for (let i of borrowIngListAllData.value) {
        if (item.value.data.key === i.fileList.id) {
          getFindBorrowTypeByFileName(i.fileList.id);
          selectFilename.value = i.fileList.name;

          for (let j in i.fileList) {
            // 借阅档案列表（申请，编辑）
            if (['ADD', 'UPDATE'].includes(state.showType)) {
              for (let k in borrowingListAddQuestions[0].value[item.value.index]) {
                if (k === j) {
                  borrowingListAddQuestions[0].value[item.value.index][k] = i.fileList[j];
                  borrowingListAddQuestions[0].value[item.value.index].id = i.fileList.id;
                }
              }
              // borrowingListAddQuestions[0].value[item.value.index]['isDownoad'] = 1; // 是否下载，默认 是
              // borrowingListAddQuestions[0].value[item.value.index]['borrowForm'] = 1; // 外借形式，默认 是
            }
          }
        }
      }
      borrowingListAddQuestions[0].value[item.value.index]['borrowType'] = null;
      borrowingListAddQuestions[0].value[item.value.index]['isDownoad'] = null;
      borrowingListAddQuestions[0].value[item.value.index]['borrowForm'] = null;
    } else if (item.key === 'CUSTOMSELECTSERVE' && item.value.key === 'borrowType') {
      // 借阅类型
      if ([2, 3].includes(item.value.data.value)) {
        // 借阅类型为电子件、声像档案显示是否下载字段，默认 是
        borrowingListAddQuestions[0].value[item.value.index]['isDownoad'] = 1;
      } else {
        borrowingListAddQuestions[0].value[item.value.index]['isDownoad'] = null;
      }
      if ([1, 4].includes(item.value.data.value)) {
        // 借阅类型为纸质档案，实物档案显示是否外借形式，默认 外借
        borrowingListAddQuestions[0].value[item.value.index]['borrowForm'] = 1;
      } else {
        borrowingListAddQuestions[0].value[item.value.index]['borrowForm'] = null;
      }
      // for (let i of borrowIngListAllData.value) {
      //   if (item.value.data.value === i.fileList.borrowType && selectFilename.value === i.fileList.name) {
      //     for (let j in i.fileList) {
      //       // 借阅档案列表（申请，编辑）
      //       if (['ADD', 'UPDATE'].includes(state.showType)) {
      //         for (let k in borrowingListAddQuestions[0].value[item.value.index]) {
      //           if (k === j) {
      //             borrowingListAddQuestions[0].value[item.value.index][k] = i.fileList[j];
      //             borrowingListAddQuestions[0].value[item.value.index].id = i.fileList.id;
      //           }
      //         }
      //       }
      //     }
      //   }
      // }
    }
  });

const subscribePubSub = proxy.$NotificationPubSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '预览') {
      advancedQueryPreview({ id: item.value.data.fileListList.id, needRecord: false }).then((res) => {
        if (res && res.success) {
          window.open(res.data);
        }
      });
    } else if (item.key === 'DYNAMICLOCALTABLE' && item.value.part.text === '下载') {
      const url = `${searchManageApi.advancedQueryDownload}/${item.value.data.fileListList.id}`;
      downloadFile(url);
    }
  });

onMounted(async () => {
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }

  if (['ADD', 'UPDATE'].includes(state.showType)) {
    await getFindFileListByFileName();
    // 普通用户查询跳借阅
    setTimeout(() => {
      if (query.showType === 'ADD' && query.ids) {
        if (!Array.isArray(query.ids)) {
          query.ids = [query.ids];
        }
        // 过滤文件列表中地址栏id不存在的选项
        query.ids = query.ids.filter((id) => borrowIngListAllData.value.some((item) => item.fileList.id === id));
        query.ids.forEach((item, index) => {
          let obj = {};
          borrowingListAddQuestions[0].state.columns.map((key) => {
            if (borrowingListAddQuestions[0].state.default) {
              obj[key.key] = borrowingListAddQuestions[0].state.default[key];
            } else {
              obj[key.key] = null;
            }
          });
          borrowingListAddQuestions[0].value.push(obj);

          for (let i of borrowIngListAllData.value) {
            if (item === i.fileList.id) {
              getFindBorrowTypeByFileName(i.fileList.id);
              selectFilename.value = i.fileList.name;
              for (let j in i.fileList) {
                // 借阅档案列表（申请，编辑）
                if (['ADD', 'UPDATE'].includes(state.showType)) {
                  for (let k in borrowingListAddQuestions[0].value[index]) {
                    if (k === j) {
                      borrowingListAddQuestions[0].value[index][k] = i.fileList[j];
                      borrowingListAddQuestions[0].value[index].id = i.fileList.id;
                    }
                  }
                  // borrowingListAddQuestions[0].value[item.value.index]['isDownoad'] = 1; // 是否下载，默认 是
                  // borrowingListAddQuestions[0].value[item.value.index]['borrowForm'] = 1; // 外借形式，默认 是
                }
              }
            }
          }
          borrowingListAddQuestions[0].value[index]['borrowType'] = null;
          borrowingListAddQuestions[0].value[index]['isDownoad'] = null;
          borrowingListAddQuestions[0].value[index]['borrowForm'] = null;
        });
        borrowingListAddQuestions[0].value = borrowingListAddQuestions[0].value.filter((item) => item.filesBoxCode !== null);
      }
    }, 1000);

    // 通过字典编码获取key-value
    state.borrowTypeDictionary = Object.assign({}, formStore.getDictionary['DMS_ARCHIVES_FILE_BORROW_BORROW_TYPE']);
  }

  if (['UPDATE'].includes(state.showType)) {
    getBorrowFileUpdateList();

    // 借阅信息回显
    const time = setTimeout(() => {
      borrowInformation.value.getData();
      clearTimeout(time);
    }, 1000);
  }
});

onBeforeUnmount(() => {
  subscribeFormSub && subscribeFormSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
  subscribePubSub && subscribePubSub.unsubscribe();
  proxy.$NotificationPubSub.clearParams();
});

// 获取借阅档案列表文件名称
const getFindFileListByFileName = () => {
  archivesBorrowFindFileListByFileName({ fileName: '' }).then((res) => {
    if (res && res.success) {
      let arr = [];
      for (let i of res.data) {
        arr.push({ label: i.fileList.name, value: i.fileList.id, key: i.fileList.id });
      }

      // 借阅档案列表（申请，编辑）
      if (['ADD', 'UPDATE'].includes(state.showType)) {
        borrowingListAddQuestions[0].state.columns[1].options = [...arr]; // 文件名称选项
      }

      borrowIngListAllData.value = [...res.data];
    }
  });
};

// 通过文件名称获取可以借阅的类型
const getFindBorrowTypeByFileName = (id) => {
  archivesBorrowFindBorrowType(id, {}).then((res) => {
    if (res && res.success) {
      let arr = [];
      for (let i of res.data) {
        arr.push({ label: state.borrowTypeDictionary[i], value: i, key: i });
      }
      borrowingListAddQuestions[0].state.columns[3].options = [...arr]; // 借阅类型选项
    }
  });
};

const borrowingDurationObj = reactive<{ isLargerThan: Boolean; borrowDurationData: Number }>({
  isLargerThan: false, // 借阅时间是否大于5天
  borrowDurationData: 1
});

// 借阅时间失去焦点事件
const borrowDurationBlur = (e, data) => {
  if (e.isTrusted && typeof data !== 'undefined') {
    if (data > 5) {
      borrowingDurationObj.isLargerThan = true;
    } else {
      borrowingDurationObj.isLargerThan = false;
    }

    borrowingDurationObj.borrowDurationData = data;
  }
};

const hasLargerThan = computed(() => {
  return dayjs().add(borrowingDurationObj.borrowDurationData, 'day').subtract(3, 'day').format('YYYY.MM.DD HH:mm:ss');
});

const hasLessThan = computed(() => {
  return dayjs().add(borrowingDurationObj.borrowDurationData, 'day').subtract(1, 'day').format('YYYY.MM.DD HH:mm:ss');
});

// 保存
const savePageInfo = (op) => {
  Modal.confirm({
    title: `是否确定${op === 0 ? '暂存' : '提交'}`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      let beforeSaveData = {
        baseData: {},
        borrowListData: [],
        borrowInformationData: {}
      };
      base.value.onFinish(({ billCode, creator, creatorName, department, departmentName, createdTime }) => {
        beforeSaveData.baseData = Object.assign({}, { billCode, creator, creatorName, department, departmentName, createdTime });
      });
      borrowList.value.onFinish((data) => {
        for (let { borrowCode, isDownoad, borrowType, borrowForm, name, code, fileCode, filesType, secretLevel, filesBoxCode, id } of data.customTable) {
          // let fileListList = {};
          // fileListList = Object.assign({}, i);
          // delete fileListList['borrowCode'];
          // delete fileListList['isDownoad'];
          // delete fileListList['borrowType'];
          // delete fileListList['borrowForm'];

          // let fileList = {};
          // fileList['borrowCode'] = i.borrowCode;
          // fileList['isDownoad'] = i.isDownoad;
          // fileList['borrowType'] = i.borrowType;
          // fileList['borrowForm'] = i.borrowForm;
          // fileList['fileListList'] = { ...fileListList };

          let fileList = {};
          fileList['fileListList'] = { name, code, fileCode, filesType, secretLevel, filesBoxCode, id };

          if (['ADD'].includes(state.showType)) {
            fileList = Object.assign(fileList, { isDownoad, borrowType, borrowForm });
          }

          if (['UPDATE'].includes(state.showType)) {
            fileList = Object.assign(fileList, { isDownoad, borrowType, borrowForm, borrowCode });
          }

          beforeSaveData.borrowListData.push(fileList);
        }
      }, op == 0);
      borrowInformation.value.onFinish(({ borrowTime, borrowDuration, borrowReason, remark, expirationReminder }) => {
        beforeSaveData.borrowInformationData = Object.assign({}, { borrowTime, borrowDuration, borrowReason, remark, expirationReminder });
      }, op == 0);

      const time = setTimeout(() => {
        if (op == 0 || (Object.keys(beforeSaveData.baseData).length > 0 && beforeSaveData.borrowListData.length && Object.keys(beforeSaveData.borrowInformationData).length > 0)) {
          let finalSaveData = { ...beforeSaveData.baseData, fileList: [...beforeSaveData.borrowListData], ...beforeSaveData.borrowInformationData };
          finalSaveData['borrowDuration'] = borrowingDurationObj.borrowDurationData;

          // 到期提醒时间
          let expirationReminderTime = null;
          if (borrowingDurationObj.isLargerThan) {
            expirationReminderTime = hasLargerThan.value.replace(/\./gi, '-');
          } else {
            expirationReminderTime = hasLessThan.value.replace(/\./gi, '-');
          }
          finalSaveData['expirationReminder'] = expirationReminderTime;

          archivesBorrowSave({ ...finalSaveData, op: op, id: ['UPDATE'].includes(state.showType) ? query.id : null }).then((res) => {
            if (res && res.success) {
              message.success(res.message);
              goBack();
            }
          });
        }
        clearTimeout(time);
      }, 1000);
    }
  });
};

// 审核
const reviewSubmit = () => {
  approvalOpinions.value.onFinish((data) => {
    let { id, applyResult, remark } = data;

    archivesBorrowAudit({ billId: id, applyResult, remark }).then((res) => {
      if (res && res.success) {
        message.success(res.message);
        goBack();
      }
    });
  });
};

// 编辑时，获取借阅档案列表
const getBorrowFileUpdateList = () => {
  archivesBorrowGetBorrowFileList({ id: query.id }).then((res) => {
    if (res && res.success) {
      let arr = [];
      for (let i of res.data) {
        let obj = { ...i };
        delete obj['fileListList'];
        obj = Object.assign(obj, i.fileListList);
        arr.push(obj);
      }

      borrowingListAddQuestions[0].value = [...arr];
    }
  });
};

const goBack = () => {
  router.go(-1);
};

// 编辑页路由跳转
const toUpdate = () => {
  router
    .replace({
      name: 'ArchivesManageAddBorrow',
      query: {
        id: query.id,
        showType: 'UPDATE'
      }
    })
    .then(() => {
      router.go(0);
    });
};

// 下载文件
const downloadFile = (url) => {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', `${HOST}${url}`, true);
  xhr.setRequestHeader('token', accessToken);
  xhr.responseType = 'blob';
  xhr.onload = function () {
    if (this.status == 200) {
      const blob = new Blob([this.response], { type: 'contentType' });
      const contentDisposition = xhr.getResponseHeader('content-disposition');
      let filename = contentDisposition.substring(contentDisposition.indexOf('filename')).replace(/"/gi, '');
      filename = window.decodeURIComponent(filename.substring(filename.indexOf('=') + 1));
      const a = document.createElement('a');
      a.href = window.URL.createObjectURL(blob);
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };
  xhr.send();
};
</script>
